const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    // this.modelInstance = this.model('supervison_project');
  }

  /**
	 * 获取代理商的信息
	 * @return {[type]} [description]
	 */
  async getAction() {
    let data;
    const map = {};
    // 获取详情
    if (this.id) {
      map.id = this.id;
      data = await this.modelInstance.where(map).find();
      return this.success(data);
    }

    if (this.get('all')) {
      data = await this.modelInstance.order('id desc').select();
      return this.success(data);
    }

    // 关键词
    const key = this.get('key');
    if (key) {
      map['title|account'] = ['like', '%' + key + '%'];
    }

    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 10;
    data = await this.modelInstance.where(map).page(page, pageSize).order('id desc').countSelect();

    return this.success(data);
  }

  async postAction() {
    const data = this.post();

    delete data['id'];
    // data['create_time'] = Math.round((new Date()).getTime() / 1000);
    const ret = await this.modelInstance.add(data);

    think.logger.debug(ret);
    return this.success(ret);
  }

  // 更新用户信息
  async putAction() {
    const data = this.post();
    if (think.isEmpty(data)) {
      return this.fail(1000, '数据不能为空');
    }

    if (think.isEmpty(this.id)) {
      return this.fail(1000, '数据不能为空');
    }

    const rows = await this.modelInstance.where({ id: this.id }).update(data);
    if (rows) {
      return this.success({ affectedRows: rows }, '更新成功');
    } else {
      return this.fail(1000, '更新失败');
    }
  }
};
